/**
 * 截取字符
 */
function strtingSlice(t, e) {
    for (var n = 0, r = 0; r < (e || 511);) {
        r += t.charCodeAt(n) > 255 ? 2 : 1, n++;
    }
    return t.slice(0, n)
}

/**
 * 获取字符长度
 *
 */
function charLen(t) {
    for (var e = 0, n = t.length; n--;) {
        e += t.charCodeAt(n) > 255 ? 2 : 1;
    }
    return e
}

/**
 * 来源入口
 */
function source() {
    return [
        ["baidu", "wd"],
        ["baidu", "word"],
        ["images.google", "q"],
        ["google", "q"],
        ["yahoo", "p"],
        ["msn", "q"],
        ["live", "q"],
        ["soso", "w"],
        ["sogou", "query"],
        ["bing", "q"],
        ["so.360.cn", "q"],
        ["so.com", "q"],
        ["haosou.com", "q"],
        ["haoso.com", "q"],
        ["easou", "q"],
        ["sm.cn", "q"],
        ["youdao", "q"]
    ]
}

/**
 * 获取url参数
 * getUlrParse('http&id=12&name=32')
 */
function getUlrParse(t) {
    return t = t || window.location.search || window.location.hash, t.replace(/^.*\?/, "").split("&").map(function(t) {
        return t.split("=")
    }).reduce(function(t, e) {
        return e[0].trim() && (t[e[0]] = e[1]), t
    }, {})
}

/**
 *  回调
 */
var headCalk = function(t) {
    var e;
    return function() {
        return "undefined" == typeof e && (e = t.apply(this, arguments)), e
    }
}
/**
 * 判断iE
 */
var aa = headCalk(function() {
    return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())
})
/**
 * 获取head内容
 */
var head = headCalk(function() {
    return document.head || document.getElementsByTagName("head")[0]
})


/**
 * 判断协议
 */
function isNotHttp(state, http) {
    if (http = http.split(":")[0], state = +state, !state) return !1;
    switch (http) {
        case "http":
        case "ws":
            return 80 !== state;
        case "https":
        case "wss":
            return 443 !== state;
        case "ftp":
            return 21 !== state;
        case "gopher":
            return 70 !== state;
        case "file":
            return !1
    }
    return 0 !== t
}

/**
 * 字符参数序列化
 *
 */
function strSerial(t) {
    var e = [];
    for (var n in t) t.hasOwnProperty(n) && e.push(n + "=" + t[n]);
    return e.join("&")
}

/**
 * url参数转换对象
 * parse('?id=12&name=aa')
 */
function url_parse(t) {
    for (var ex, patt = /([^=?&]+)=?([^&]*)/g,
            obj = {}; ex = patt.exec(t); obj[decodeURIComponent(ex[1])] = decodeURIComponent(ex[2]));
    return obj
}

/**
 * url转字符串
 *
 */
function url_stringify(t, e) {
    e = e || "";
    var n = [];
    "string" != typeof e && (e = "?");
    for (var r in t) i.call(t, r) && n.push(encodeURIComponent(r) + "=" + encodeURIComponent(t[r]));
    return n.length ? e + n.join("&") : ""
}

/**
 * 判断 数组 对象
 */
var hasOwp = Object.prototype.hasOwnProperty,
    toStr = Object.prototype.toString;
var tools = {
    isArray: function(t) {
        return "function" == typeof Array.isArray ? Array.isArray(t) : "[object Array]" === toStr.call(t)
    },
    isObject: function(t) {
        if (!t || "[object Object]" !== toStr.call(t)) return !1;
        var e = hasOwp.call(t, "constructor"),
            i = t.constructor && t.constructor.prototype && hasOwp.call(t.constructor.prototype, "isPrototypeOf");
        if (t.constructor && !e && !i) return !1;
        var o;
        for (o in t);
        return "undefined" == typeof o || hasOwp.call(t, o)
    }
}

/**
 * 生成 guid
 * 05009613-6542-4721-7987-512045627445
 */
function guid() {
    var time = (new Date).getTime(),
        str = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
    return str.replace(/[xy]/g, function(str, index) {

        if (index < str.length - 2) {
            var i = (time + 16 * Math.random()) % 16 | 0;
            console.log(i);
            return time = Math.floor(time / 16), ("x" === str ? i : 7 & i | 8).toString(16)
        }
        return Math.floor(10 * Math.random())
    })
}


function Performance(t) {
    this.config = extend({
        platform: document.body["data-platform"],
        service: document.body["data-service"],
        id: document.body["data-id"],
        url: document.body["data-url"],
        resValue: document.body["data-res-value"],
        conValue: document.body["data-con-value"],
        name: document.body["data-name"]
    }, t)
}

// 加载资源
function _TestResource(t, e, n) {
    e = e ? e : 500, n = n ? n : 50;
    for (var r = [], i = t.length, o = i - 1; o > 0; o--) {
        var a = {},
            s = t[o];
        a.key = s.name, a.resValue = s.responseEnd - s.requestStart, a.conValue = s.connectEnd - s.connectStart, (a.resValue >= e || a.conValue >= n) && r.push(a)
    }
    return r
}

// 页面加载时间
function _pageLoadMethod(t) {
    var e = [],
        n = {};
    n.name = "è¿›å…¥é¡µé¢çš„æ–¹å¼";
    var r = "";
    switch (t) {
        case 0:
            r = "ç‚¹å‡»é“¾æŽ¥ã€åœ°å€æ è¾“å…¥ã€è¡¨å•æäº¤ã€è„šæœ¬æ“ä½œç­‰æ–¹å¼åŠ è½½";
            break;
        case 1:
            r = "é€šè¿‡[é‡æ–°åŠ è½½]æŒ‰é’®æˆ–è€…location.reload()æ–¹æ³•åŠ è½½";
            break;
        case 2:
            r = "ç½‘é¡µé€šè¿‡[å‰è¿›]æˆ–[åŽé€€]æŒ‰é’®åŠ è½½";
            break;
        default:
            r = "ä»»ä½•å…¶ä»–æ¥æºçš„åŠ è½½"
    }
    return n.value = r, e.push(n), e
}

// 时间
function _TestTiming(t) {
    var e = [],
        n = {
            key: "DNSæŸ¥è¯¢è€—æ—¶",
            value: t.domainLookupEnd - t.domainLookupStart
        },
        r = {
            key: "TCPé“¾æŽ¥è€—æ—¶",
            value: t.connectEnd - t.connectStart
        },
        i = {
            key: "requestè¯·æ±‚è€—æ—¶",
            value: t.responseEnd - t.responseStart
        },
        o = {
            key: "è§£æždomæ ‘è€—æ—¶",
            value: t.domComplete - t.domInteractive
        },
        a = {
            key: "ç™½å±æ—¶é—´",
            value: t.responseStart - t.navigationStart
        },
        s = {
            key: "domreadyæ—¶é—´",
            value: t.domContentLoadedEventEnd - t.navigationStart
        };
    return e = e.concat(n, r, i, o, a, s)
}

// 图片错误设置
function _postByImg(t) {
    var e = new Image;
    e.onload = e.onerror = function() {
        e = null
    }, e.src = t
}

// 地址栏参数拼接
function _setParams(t) {
    var e = "";
    for (var n in t) {
        e += n + "=" + t[n] + "&";
    }
    return e = e.slice(0, e.length - 1);
}

// http创建
function _createXMLHttpRequest() {
    if (window.ActiveXObject)
        for (var t = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"], e = 0; e < t.length; e++) try {
            return new ActiveXObject(t[e])
        } catch (n) {
            continue
        } else if (window.XMLHttpRequest) return new XMLHttpRequest;
    throw new Error("XMLHttp object could not be created.")
}

// ajax
function _ajax(_options) {
    function add(t, e) {
        "undefined" === e && (e = ""), query[query.length] = t + "=" + e
    }
    var _xmlHttp = _createXMLHttpRequest(),
        query = [],
        data;
    for (var key in _options.data)
        if ("object" == typeof _options.data[key])
            for (var k in _options.data[key]) add(key + "[" + k + "]", _options.data[key][k]);
        else add(key, _options.data[key]);
    data = query.join("&"), "POST" == _options.method.toUpperCase() ? (_xmlHttp.open(_options.method, _options.url, !0), _xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")) : _xmlHttp.open(_options.method, _options.url + "?" + data, !0), _xmlHttp.onreadystatechange = function() {
        if (4 == _xmlHttp.readyState && 200 == _xmlHttp.status) {
            var response = null;
            if (_options.dataType) switch (_options.dataType.toUpperCase()) {
                case "JSON":
                    response = eval("(" + _xmlHttp.responseText + ")");
                    break;
                case "XML":
                    response = _xmlHttp.responseXML;
                    break;
                case "HTML":
                    response = _xmlHttp.responseText;
                    break;
                default:
                    response = _xmlHttp.responseText
            } else response = eval("(" + _xmlHttp.responseText + ")");
            "undefined" != typeof _options.success && _options.success(response)
        } else if (4 == _xmlHttp.readyState) {
            var codes = ["500", "501", "502", "503", "504", "505", "404"];
            codes.join(",").indexOf(_xmlHttp.status.toString()) >= 0 && "undefined" != typeof _options.error && _options.error(_xmlHttp.status, _xmlHttp.responseText)
        }
    }, "POST" == _options.method.toUpperCase() ? _xmlHttp.send(data) : _xmlHttp.send(null)
}

function _post(t, e, n) {
    _ajax({
        url: t,
        data: e,
        method: "POST",
        dataType: "json",
        success: n
    })
}

function _get(t, e, n) {
    _ajax({
        url: t,
        data: e,
        dataType: "json",
        method: "GET",
        success: n
    })
}

Performance.prototype.sendMessage = function(t) {
    if (this.config = extend(this.config, t), !("performance" in window && "getEntriesByType" in window.performance && window.performance.getEntriesByType("resource") instanceof Array)) return void console.warn("æµè§ˆå™¨ä¸æ”¯æŒperformance");
    var e = window.document.cookie,
        n = e.indexOf("gzCityDomain");
    n = n === -1 ? e.indexOf("cityDomain") : n;
    var r = "-";
    n >= 0 && (r = e.substring(n).split(";")[0].split("=")[1]);
    for (var i = _TestResource(performance.getEntries(), this.config.resValue, this.config.conValue), o = 0; o < i.length; o++) i[o].key = encodeURIComponent(i[o].key);
    var a = {
        platform: this.config.platform,
        service: this.config.service,
        id: this.config.id,
        timing: JSON.stringify(_TestTiming(performance.timing)),
        resources: JSON.stringify(i),
        useragent: navigator.userAgent,
        addressCity: r,
        localurl: window.location.href,
        typekind: JSON.stringify(_pageLoadMethod(performance.navigation))
    };
    if (this.config.url) _post(this.config.url, a, this.config.callback);
    else {
        var s = document.location.protocol + (this.config.name || "//t.guazi.com/p.gif?") + _setParams(a);
        _postByImg(s)
    }
}